package com.meng.webconfig;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;


/**
 * redis 配置类
 *
 * @EnableRedisHttpSession 开启spring session支持
 *
 * 过期时间：maxInactiveIntervalInSeconds 秒
 *
 * @author MENG
 * @version 2017/12/24
 * @see
 */
@Configuration
@EnableRedisHttpSession
public class RedisConfig extends CachingConfigurerSupport
{
    /**
     *
     * spring提供两个类操作Redis RedisTemplate(操作对象) StringRedisTemplate(操作String)
     *
     * @param factory
     * @return
     */
    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory)
    {
        StringRedisTemplate template = new StringRedisTemplate(factory);

        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper om = new ObjectMapper();

        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);

        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

        jackson2JsonRedisSerializer.setObjectMapper(om);

        template.setValueSerializer(jackson2JsonRedisSerializer);

        template.afterPropertiesSet();

        return template;
    }


    //自动根据方法生成缓存
//    @RequestMapping("/getUser")
//    @Cacheable(value="user-key")  //其中value的值就是缓存到redis中的key
//    public User getUser()
//    {
//        User user=userRepository.findByUserName("aa");

//        System.out.println("若下面没出现“无缓存的时候调用”字样且能打印出数据表示测试成功");

//        return user;
//    }
}
